import { ref, computed, onMounted} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import myaxios from '@/auth/auth.service'
import { useHome } from '@/components/composables/useHome'
import {showToastMessage} from "@/utils/message"

export function useRelicDetail() {
  const { choicesData } = useHome()
  const router = useRouter()
  const route = useRoute()

  const loading = ref(false)
  const error = ref('')
  const relicId = ref(0)
  const currentRelic = ref<any>(null)
  const currentRelicname=ref('')
  const categaryname=ref('')
  const categaryid=ref('')

  // 获取文物详情
  const fetchRelicData = async () => {
    loading.value = true
    error.value = ''

    try {
      relicId.value = parseInt(route.params.id as string, 10)
      const response = await myaxios.fetchDetail(relicId.value)
      currentRelic.value = response.data
    } catch (e) {
      console.error('获取文物数据失败', e)
      error.value = '获取文物数据失败，请重试'
    } finally {
      loading.value = false
    }
      currentRelicname.value=currentRelic.value.name
      categaryname.value=currentRelic.value.category.name
      categaryid.value=currentRelic.value.category.id
  }

  // 获取建筑类型文本（含other）
  const getBuildingTypeText = (type: string, otherType: string) => {
    if (type === 'other') {
      return otherType?.trim() || '其他'
    }
    return choicesData.value.BUILDING_TYPE_CHOICES?.[type] || type
  }

  // 格式化日期
  const formatDate = (dateString: string) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  }

  // 返回上一页
  const goBack = () => {
    router.go(-1)
  }
  const goToUser = () => {
    router.push('/personalinfo')
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }
  const gomainpage = () => {
    router.push({
      path: '/mainpage',
      query: { categoryid: categaryid.value, categoryname: categaryname.value },
    })
  }
  // 跳转编辑
  const goToEdit = () => {
    if (currentRelic.value?.id) {
      router.push(`/edit/${currentRelic.value.id}`)
    }
  }

  // 删除病害图片
  const handleDeleteImage = async (relicId: number, imageId: number) => {
    try {
      const result = await myaxios.deleteDiseaseImage(relicId, imageId)
      if (result.success) {
        currentRelic.value.disease_images = currentRelic.value.disease_images.filter(
          (img: any) => img.id !== imageId
        )
        showToastMessage("success","图片已删除成功")
      }
    } catch (err) {
      showToastMessage("error","删除失败")
    }
  }
// ✅ 正确方式：使用 computed 自动响应数据变化
  const diseaseSeverityText = computed(() => {
    const severity = currentRelic.value?.disease_severity
    if (severity === '轻微') return '轻微（<10%）'
    if (severity === '中度') return '中度（10%-50%）'
    if (severity === '严重') return '严重（>50%）'
    return '未知'
  })
  // 组件挂载时加载数据
  onMounted(() => {
    fetchRelicData()
  })

  return {
    choicesData,
    loading,
    error,
    relicId,
    currentRelic,
    currentRelicname,
    categaryid,
    categaryname,
    diseaseSeverityText,
    goHome,
    goToUser,
    goToCategory,
    gomainpage,
    fetchRelicData,
    getBuildingTypeText,
    formatDate,
    goBack,
    goToEdit,
    handleDeleteImage,
  }
}
